<template>
  <div class="app-container">
    <h3>根据光标位置插入文本</h3>
    <el-input
      type="textarea"
      id="mytextarea"
      :autosize="{ minRows: 10, maxRows: 15}"
      placeholder="请输入"
      v-model="messageTemplate.content"
    />
    <el-button @click="insertVariable">插入文本</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      messageTemplate: {
        content: ''
      },
    }
  },
  methods: {
    async insertVariable(value) {
      const myTextarea = document.querySelector('#mytextarea');
      value = "可怜今夕月,向何处,去悠悠？";
      if (myTextarea.selectionStart || myTextarea.selectionStart === 0) {
        let startPos = myTextarea.selectionStart;
        let endPos = myTextarea.selectionEnd;
        this.messageTemplate.content = myTextarea.value.substring(0, startPos) + value
                    + myTextarea.value.substring(endPos, myTextarea.value.length);
        await this.$nextTick() 
        myTextarea.focus();
        myTextarea.setSelectionRange(endPos + value.length, endPos + value.length);
      } else {
        this.messageTemplate.content = value;
      }
    }
  }
}
</script>